extern "C" {
#include <sys/types.h>
#include <sys/socket.h>
}
#include <sstream>
#include "connection.hpp"

bool Connection::send(const char* bytes, const int size) const {
  int count = size;
  const char* p = bytes;
  while (0 < count) {
    int sent = ::send(this->_soc, p, count, 0);
    if (sent < 0) {
      return false;
    }
    p += sent;
    count -= sent;
  }
  return true;
}

static const char CRLF[] = "\r\n";

bool Connection::send_http_status(const char* ver, const char* status) const {  // TODO
  std::ostringstream response;
  response << ver << " " << status << CRLF;
  response << "Content-Length: " << 0 << CRLF;
  response << CRLF;
  const std::string& res_str = response.str();
  return this->send(res_str.c_str(), res_str.size());
}

bool Connection::send_status_line(const char* ver, const char* status) const {
  std::ostringstream line;
  line << ver << " " << status << CRLF;
  const std::string& line_str = line.str();
  return this->send(line_str.c_str(), line_str.size());
}

bool Connection::send_header() const {
  std::ostringstream header;
  for (string_map::const_iterator it = this->_res.begin(); it != this->_res.end(); ++it) {
    header << (it->first) << ": " << (it->second) << CRLF;
  }
  header << CRLF;
  const std::string& header_str = header.str();
  return this->send(header_str.c_str(), header_str.size());
}

